package com.gerfmarquez.nymph.ui.listeners;

import java.util.ArrayList;
import java.util.Iterator;

import android.content.Context;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;

import com.gerfmarquez.nymph.NymphMelodyCreatorActivity;
import com.gerfmarquez.nymph.db.sqlite.DatabaseHelper;
import com.gerfmarquez.nymph.db.sqlite.NoteLengthDbAdapter;
import com.gerfmarquez.nymph.db.sqlite.SongNoteLengthDbAdapter;
import com.gerfmarquez.nymph.db.sqlite.dto.Song;

public class OnSaveSelectedMelodyListener implements DialogInterface.OnClickListener {
	ArrayList<Song> songs;
	public NymphMelodyCreatorActivity nymph;
	Context context;
	public OnSaveSelectedMelodyListener(ArrayList<Song> songs, Context context,NymphMelodyCreatorActivity nymph) {
		this.songs = songs;
		this.context = context;
		this.nymph = nymph;
	}
	@Override
	public void onClick(DialogInterface arg0, int arg1) {
		// TODO Auto-generated method stub
    	DatabaseHelper dbHelper = new DatabaseHelper(context);
    	SQLiteDatabase database =dbHelper.getWritableDatabase();
    	
    	Iterator<Song> it = songs.iterator();
    	
    	while(it.hasNext()) {
    		Song songTemp = it.next();
    		if(songTemp.getItem() == arg1) {
    			SongNoteLengthDbAdapter sNLDA = new SongNoteLengthDbAdapter(database);
    			
    			int idSong = songTemp.getIdSong();
    			sNLDA.deleteSongNoteLength(idSong);
    			
    			int[] notes = nymph.getNotesFromSlideViews();
    			byte[] rhythms = nymph.getNotesRhythm();
    	    	
    			for(int i = 0; i < notes.length; i++ ) {
    				NoteLengthDbAdapter noteLengthAdapter = new NoteLengthDbAdapter(database);
    				int idNoteLength = noteLengthAdapter.getNoteLengthId((int)rhythms[i]);
    				sNLDA.createSongNoteLength(idSong, notes[i],idNoteLength);
    			}
    			break;
    		}
    	}
    	
    	
    	dbHelper.close();
	}
}


